package sealte.util.xml;

import java.io.OutputStream;

import org.jdom2.Attribute;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;

public class XMLCreater {
	
	private Element root = null;
	private OutputStream os = null;	
	private Format format = null;
	private Document doc = null;
	private XMLOutputter out = null;
	
	public XMLCreater(String rootElementName){
		this.root = new Element(rootElementName);
		this.format = Format.getCompactFormat();
		this.doc = new Document();
		this.doc.setRootElement(this.root);
		this.out = new XMLOutputter();
	}
	
	public XMLCreater(String rootElementName,OutputStream outputStream){
		this.root = new Element(rootElementName);
		this.os = outputStream;
		this.format = Format.getCompactFormat();
		this.doc = new Document();
		this.doc.setRootElement(this.root);
		this.out = new XMLOutputter();
	}
	
	public void setFormat(String encoding,String indent){
		this.format.setEncoding(encoding);
		this.format.setIndent(indent);
		this.out.setFormat(this.format);
	}
	
	public void addElement(String elementName,String elementText,String[] path) throws Exception {
		Element current = new Element(elementName);
		current.setText(elementText);
		Element parent = XMLReader.getElement(this.root, path);
		parent.addContent(current);
	}
	
	public void setAttribute(String attributeName,String attributeValue,String[] path) throws Exception {
		Attribute att = new Attribute(attributeName,attributeValue);
		Element current = XMLReader.getElement(this.root, path);
		current.setAttribute(att);
	}
	
	public void createFile() throws Exception {
		this.out.output(this.doc, this.os);
	}
	
	public String createString() throws Exception {
		return this.out.outputString(this.doc);
	}
}
